<?php
/**
 * Web版手动安装脚本
 * 直接在浏览器中运行此文件来安装系统
 */

// 数据库配置
$db_config = [
    'host' => 'localhost',
    'username' => 'worklog_kukudb_c',
    'password' => '',
    'database' => 'worklog_kukudb_c',
    'charset' => 'utf8mb4'
];

$results = [];
$successCount = 0;
$errorCount = 0;

if ($_POST && $_POST['action'] === 'install') {
    try {
        // 连接数据库
        $dsn = "mysql:host={$db_config['host']};dbname={$db_config['database']};charset={$db_config['charset']}";
        $pdo = new PDO($dsn, $db_config['username'], $db_config['password']);
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        
        $results[] = ['type' => 'success', 'message' => '数据库连接成功！'];
        
        // 读取SQL文件
        $sqlFile = __DIR__ . '/sql/database.sql';
        if (file_exists($sqlFile)) {
            $sql = file_get_contents($sqlFile);
            
            // 先删除已存在的表
            $tables = ['users', 'attendance_records', 'system_config', 'overtime_records', 'leave_records', 'business_trips'];
            foreach ($tables as $table) {
                try {
                    $pdo->exec("DROP TABLE IF EXISTS `{$table}`");
                    $results[] = ['type' => 'success', 'message' => '删除表成功: ' . $table];
                } catch (Exception $e) {
                    // 忽略删除表时的错误
                }
            }
            
            // 分割SQL语句
            $queries = array_filter(array_map('trim', explode(';', $sql)));
            
            foreach ($queries as $query) {
                if (!empty($query)) {
                    try {
                        $pdo->exec($query);
                        $results[] = ['type' => 'success', 'message' => '执行成功: ' . substr($query, 0, 50) . '...'];
                        $successCount++;
                    } catch (Exception $e) {
                        $results[] = ['type' => 'error', 'message' => '执行失败: ' . $e->getMessage() . ' SQL: ' . substr($query, 0, 100) . '...'];
                        $errorCount++;
                    }
                }
            }
            
            // 创建管理员账号
            $adminPassword = 'admin123';
            $hashedPassword = password_hash($adminPassword, PASSWORD_DEFAULT);
            
            try {
                $stmt = $pdo->prepare("INSERT INTO users (username, password, role, email, full_name, department, position, status) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                $stmt->execute([
                    'admin',
                    $hashedPassword,
                    'super_admin',
                    'admin@example.com',
                    '系统管理员',
                    'IT部门',
                    '系统管理员',
                    1
                ]);
                $results[] = ['type' => 'success', 'message' => '管理员账号创建成功'];
                $successCount++;
            } catch (Exception $e) {
                $results[] = ['type' => 'error', 'message' => '创建管理员账号失败: ' . $e->getMessage()];
                $errorCount++;
            }
            
            // 创建配置文件
            $configContent = "<?php\nreturn [\n    'db' => [\n";
            foreach ($db_config as $key => $value) {
                $configContent .= "        '{$key}' => '{$value}',\n";
            }
            $configContent .= "    ],\n    'system' => [\n        'title' => '考勤管理系统',\n        'version' => '1.0.0',\n        'debug' => false\n    ]\n];\n";
            
            if (file_put_contents(__DIR__ . '/config.inc.php', $configContent) === false) {
                $results[] = ['type' => 'error', 'message' => '无法创建配置文件'];
                $errorCount++;
            } else {
                $results[] = ['type' => 'success', 'message' => '配置文件创建成功'];
                $successCount++;
            }
            
        } else {
            $results[] = ['type' => 'error', 'message' => '数据库SQL文件不存在: ' . $sqlFile];
            $errorCount++;
        }
        
    } catch (PDOException $e) {
        $results[] = ['type' => 'error', 'message' => '数据库连接失败: ' . $e->getMessage()];
        $errorCount++;
    }
}
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>考勤管理系统 - Web安装</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
        }
        .install-container {
            background: white;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
            overflow: hidden;
            max-width: 800px;
            margin: 0 auto;
        }
        .install-header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }
        .install-body {
            padding: 2rem;
        }
        .result-item {
            padding: 10px;
            margin: 5px 0;
            border-radius: 5px;
        }
        .result-success {
            background-color: #d4edda;
            border-left: 4px solid #28a745;
        }
        .result-error {
            background-color: #f8d7da;
            border-left: 4px solid #dc3545;
        }
    </style>
</head>
<body>
    <div class="install-container">
        <div class="install-header">
            <h1><i class="fas fa-clock me-2"></i>考勤管理系统</h1>
            <p class="mb-0">Web手动安装</p>
        </div>
        
        <div class="install-body">
            <h3 class="mb-4">手动安装系统</h3>
            
            <div class="alert alert-info">
                <h5><i class="fas fa-info-circle me-2"></i>安装信息</h5>
                <p><strong>数据库主机:</strong> <?php echo $db_config['host']; ?></p>
                <p><strong>数据库用户:</strong> <?php echo $db_config['username']; ?></p>
                <p><strong>数据库名称:</strong> <?php echo $db_config['database']; ?></p>
                <p class="mb-0">点击下面的按钮开始安装。</p>
            </div>
            
            <?php if (!empty($results)): ?>
                <div class="mb-4">
                    <h5>安装结果：</h5>
                    <?php foreach ($results as $result): ?>
                        <div class="result-item <?php echo $result['type'] === 'success' ? 'result-success' : 'result-error'; ?>">
                            <?php if ($result['type'] === 'success'): ?>
                                <i class="fas fa-check text-success me-2"></i>
                            <?php else: ?>
                                <i class="fas fa-times text-danger me-2"></i>
                            <?php endif; ?>
                            <?php echo $result['message']; ?>
                        </div>
                    <?php endforeach; ?>
                    
                    <div class="mt-3">
                        <h5>安装统计：</h5>
                        <p>成功: <span class="text-success"><?php echo $successCount; ?></span> 条</p>
                        <p>失败: <span class="text-danger"><?php echo $errorCount; ?></span> 条</p>
                    </div>
                    
                    <?php if ($errorCount === 0): ?>
                        <div class="alert alert-success mt-3">
                            <h5><i class="fas fa-check-circle me-2"></i>安装成功！</h5>
                            <p><strong>默认管理员账号：</strong></p>
                            <p>用户名: admin</p>
                            <p>密码: admin123</p>
                            <p class="mb-0"><a href="index.php" class="btn btn-success">访问系统</a></p>
                        </div>
                    <?php else: ?>
                        <div class="alert alert-warning mt-3">
                            <h5><i class="fas fa-exclamation-triangle me-2"></i>安装过程中出现错误</h5>
                            <p class="mb-0">请检查错误信息并重新安装。</p>
                        </div>
                    <?php endif; ?>
                </div>
            <?php endif; ?>
            
            <form method="post">
                <input type="hidden" name="action" value="install">
                <div class="text-center">
                    <button type="submit" class="btn btn-primary btn-lg">
                        <i class="fas fa-cog me-2"></i>开始安装
                    </button>
                </div>
            </form>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/js/all.min.js"></script>
</body>
</html>
